<template>
    <page-box class="custom-page-box">
        <template v-slot:header>
            <ask-breadcrumb>
                <template
                    v-for="(item, index) in $getBreadCrumbsName($route.path)"
                >
                    <ask-breadcrumb-item
                        :key="index"
                        v-if="item.path"
                        :to="'/' + item.path"
                        >{{ item.meta.title }}</ask-breadcrumb-item
                    >
                    <ask-breadcrumb-item :key="index" v-else>{{
                        item.meta.title
                    }}</ask-breadcrumb-item>
                </template>
            </ask-breadcrumb>
        </template>
        <div class="regional-table-container">
            <page-card
                v-if="$route.query.areaName"
                :label="$route.query.areaName"
            ></page-card>
            <ask-auth slim rules="add">
                <page-search>
                    <page-search-column class="fixed-column">
                        <div class="pbb__search-group left">
                            <div class="pbb__search-info">
                                <el-button
                                    class="pbb__search-btn"
                                    type="primary"
                                    @click="toEdit()"
                                    icon="el-icon-plus"
                                >
                                    {{ getLevelInfo.btnText }}
                                </el-button>
                            </div>
                        </div>
                    </page-search-column>
                </page-search>
            </ask-auth>
            <el-table
                ref="multipleTable"
                :data="tableData"
                class="pbb__table"
                header-cell-class-name="pbb__table-thead"
                cell-class-name="pbb__table-thead-cell"
                row-class-name="pbb__table-thead-row"
                row-key="superAdminId"
                @selection-change="onTableSelectionChange"
                @sort-change="sortChange"
                style="width: 100%; height: calc(100% - 58px); overflow-y: auto"
                :key="key"
            >
                <el-table-column
                    align="center"
                    type="selection"
                    :reserve-selection="true"
                    width="60"
                >
                </el-table-column>
                <el-table-column
                    label="序号"
                    align="center"
                    type="index"
                    width="60"
                >
                </el-table-column>
                <el-table-column
                    :label="
                        $route.name === 'RegionalVillage'
                            ? '村名称'
                            : '区域名称'
                    "
                    :label-class-name="
                        form.govId ? 'table-header-is-select' : ''
                    "
                    prop="governmentName"
                    min-width="220"
                >
                    <template slot="header" v-if="!$route.query.govId">
                        <header-filter
                            type="regional"
                            @close="filterClose($event, 'govId')"
                        >
                            <span class="table-header-filter"
                                >{{
                                    $route.name === "RegionalVillage"
                                        ? "村(社)名称"
                                        : "区域名称"
                                }}<i class="el-icon-caret-bottom"></i
                            ></span>
                        </header-filter>
                    </template>
                </el-table-column>
                <el-table-column
                    v-if="$route.name !== 'RegionalVillage'"
                    prop="count"
                    :label="
                        $route.name === 'RegionalArea'
                            ? '开通镇数量'
                            : '开通村数量'
                    "
                    min-width="90"
                    show-overflow-tooltip
                >
                </el-table-column>
                <el-table-column
                    v-if="$route.name !== 'RegionalVillage'"
                    prop="startTime"
                    label="开通时间"
                    :label-class-name="
                        form.startTime ? 'table-header-is-select' : ''
                    "
                    min-width="170"
                >
                    <template slot="header">
                        <header-filter
                            type="daterange"
                            @close="filterClose($event, 'startTime')"
                        >
                            <span class="table-header-filter"
                                >开通时间<i class="el-icon-caret-bottom"></i
                            ></span>
                        </header-filter>
                    </template>
                </el-table-column>
                <el-table-column
                    v-if="$route.name !== 'RegionalVillage'"
                    prop="endTime"
                    label="到期时间"
                    :label-class-name="
                        form.endTime ? 'table-header-is-select' : ''
                    "
                    show-overflow-tooltip
                    min-width="170"
                >
                    <template slot="header">
                        <header-filter
                            type="daterange"
                            @close="filterClose($event, 'endTime')"
                        >
                            <span class="table-header-filter"
                                >到期时间<i class="el-icon-caret-bottom"></i
                            ></span>
                        </header-filter>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="superAdmin"
                    :label="
                        $route.name === 'RegionalVillage'
                            ? '村管理员账号'
                            : '超管账号'
                    "
                    show-overflow-tooltip
                    min-width="140"
                >
                </el-table-column>
                <el-table-column
                    prop="createUser"
                    label="开通人"
                    show-overflow-tooltip
                    min-width="120"
                >
                </el-table-column>
                <el-table-column
                    prop="createTime"
                    label="开通时间"
                    sortable="custom"
                    show-overflow-tooltip
                    min-width="170"
                >
                </el-table-column>
                <el-table-column
                    v-if="client === 'OPERATION_ADMIN'"
                    prop="status"
                    label="状态"
                    show-overflow-tooltip
                    min-width="140"
                >
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.status"
                            @change="changeState($event, scope.row)"
                            :active-value="1"
                            :inactive-value="2"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            active-text="启用"
                            inactive-text="禁用"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    show-overflow-tooltip
                    min-width="120"
                >
                    <template slot-scope="scope">
                        <ask-auth slim rules="update">
                            <el-button
                                v-if="checkAuth(scope.row)"
                                type="text"
                                @click="toEdit(scope.row)"
                                >编辑</el-button
                            >
                        </ask-auth>
                        <el-button
                            type="text"
                            @click="toTown(scope.row)"
                            v-if="$route.name === 'RegionalArea'"
                            >镇</el-button
                        >
                        <el-button type="text" @click="changeArea(scope.row)"
                            >切换</el-button
                        >
                        <el-button type="text" v-if="['2','4','6'].includes(scope.row.createUserCategoryId) && $route.name === 'RegionalVillage'" @click="toVillage(scope.row)"
                            >配置</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <template v-slot:footer v-if="total > 0">
            <div class="page-base-footer__right">
                <div class="num-box">
                    已选<span>{{ batchList.length }}</span
                    >条
                </div>
                <el-divider direction="vertical"></el-divider>
                <ask-auth slim rules="remove">
                    <el-button
                        plain
                        @click="deleteRow"
                        icon="el-icon-delete-solid"
                        :disabled="batchList.length === 0 || !canBatch.remove"
                        >批量删除</el-button
                    >
                </ask-auth>
            </div>
            <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="pageIndex"
                :limit.sync="pageSize"
                @pagination="getTable"
            />
        </template>
    </page-box>
</template>

<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import HeaderFilter from "@/components/header-filter/index.vue";
import { State } from "vuex-class";
import { dialogForm } from "../components/regional-manage/form";

export interface Form {
    govId: string;
    startTime: string;
    endTime: string;
}
@Component({
    name: "RegionalNotAlive",
    components: {
        HeaderFilter
    }
})
export default class RegionalNotAlive extends Vue {
    @State((state) => state.authArea) authArea: any;
    // 当前用户所处层级菜单
    get client() {
        return this.$getUserLevel(this.authArea && this.authArea.orgCategoryId)
            .name;
    }

    get _isOperation() {
        return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(this.client);
    }
    
    key = 0;
    // 批量操作数据集合
    batchList: any[] = [];
    canBatch: any = {
        // 是否可以批量删除
        remove: false
    };

    // 表格数据
    tableData: any = [];
    // 总数
    total = 0;
    // 页码
    pageIndex = 1;
    // 每页数量
    pageSize = 10;
    // 选中内容
    multipleSelection: any = [];
    form: Form = {
        govId: "",
        startTime: "",
        endTime: ""
    };

    get getLevelInfo() {
        const _name = this.$route.name;
        if (_name === "RegionalArea") {
            return {
                menu: "MenuAreaManage",
                btnText: "开通区县市",
                type: 0
            };
        } else if (_name === "RegionalTown") {
            return {
                menu: "MenuAreaManage",
                btnText: "开通乡镇",
                type: 1
            };
        } else {
            return {
                menu: "MenuAreaManage",
                btnText: "开通村域",
                type: 2
            };
        }
    }

    @Watch("$route", { immediate: false, deep: true })
    routeChange() {
        const name = this.$route.name || "";
        if (
            ["RegionalArea", "RegionalTown", "RegionalVillage"].includes(name)
        ) {
            this.key++;
            this.form = {
                govId: "",
                startTime: "",
                endTime: ""
            };
            this.initData();
        }
    }

    // 排序
    sortType = "desc";

    created() {
        this.initData();
    }

    initData() {
        this.getTable();
    }

    // 关闭表头筛选
    filterClose(data: any, field: string) {
        this.form[field] = data.data;
        this.getTable();
    }

    toVillage(item: any) {
        this.$router.push({
            name: "SystemVillageDes",
            query: {
                cityCode: item.cityCode
            }
        });
    }

    // 获取表格数据
    getTable() {
        const { govId, startTime, endTime } = this.form;
        this.$server["regional/getTable"]({
            data: {
                governmentId: this.$route.query.govId || govId || "",
                pageSize: this.pageSize,
                currentPage: this.pageIndex,
                type: this.getLevelInfo.type,
                startTimeStart: startTime ? startTime[0] : "",
                startTimeEnd: startTime ? startTime[1] : "",
                endTimeStart: endTime ? endTime[0] : "",
                endTimeEnd: endTime ? endTime[1] : "",
                order: this.sortType
            }
        })
            .then((res: any) => {
                if (res.data.code === 200) {
                    this.tableData = res.data.data.records || [];
                    this.total = res.data.data.total;
                } else {
                    this.$message.error(res.data.message || "接口请求错误!");
                }
            })
            .catch();
    }

    handleBatchClick(command: any) {
        if (command === "remove") {
            this.deleteRow();
        }
    }

    // 表格选中修改
    onTableSelectionChange(selectList: any[]) {
        const removeList = selectList;
        this.canBatch.remove = removeList.length === selectList.length;
        this.batchList = selectList;
    }

    // 排序修改
    sortChange(colData: any) {
        this.sortType = colData.order === "ascending" ? "asc" : "desc";
        this.tableData = [];
        this.pageIndex = 1;
        this.getTable();
    }

    // 删除行
    deleteRow() {
        this.$confirm("删除后将丢失全部相关数据 是否确认删除？", "提示")
            .then(() => {
                this.changeState("delete", this.batchList);
                this.onTableSelectionChange([]);
            })
            .catch();
    }

    // 修改禁用启用状态
    changeState(val: any, row: any) {
        this.$server["regional/changeAccount"]({
            data: {
                userIds:
                    val === "delete"
                        ? row.map((item: any) => item.superAdminId).join(",")
                        : row.superAdminId,
                status: val === "delete" ? undefined : val,
                delete: val === "delete" ? true : ""
            }
        }).then((res: any) => {
            if (res.data.code === 200) {
                this.getTable();
            } else {
                if (val === "delete") {
                    row.status = val === 1 ? 2 : 1;
                }
                this.$message.error(res.data.message);
            }
        });
    }

    // 去编辑
    toEdit(row?: any) {
        let url = "";
        switch (this.$route.name) {
        case "RegionalArea":
            url = "/system-manage/update";
            break;
        case "RegionalTown":
            url = ["OPERATION", "OPERATION_ADMIN", "ADMIN"].includes(
                this.client
            )
                ? "/system-manage/update-operateTown"
                : "/system-manage/update-town";
            break;
        case "RegionalVillage":
            url = "/system-manage/update-village";
            break;
        }
        if (
            url === "/system-manage/update-village" ||
            url === "/system-manage/update-town"
        ) {
            dialogForm({
                id: row && row.superAdminId,
                name:
                    this.$route.name === "RegionalVillage"
                        ? "RegionalUpdateVillage"
                        : "RegionalUpdateTown",
                isOperation: this._isOperation,
                sure: (vm: any) => {
                    vm.close();
                    this.initData();
                }
            });
        } else {
            this.$router.push({
                path: url,
                query: { id: row && row.superAdminId }
            });
        }
    }

    // 去镇域
    toTown(row: any) {
        this.$router.push({
            path: "/system-manage/town",
            query: {
                govId: row.governmentId,
                areaName: row.governmentName
            }
        });
    }

    changeArea(row: any) {
        this.$store.dispatch("updateAuthArea", {
            id: row.governmentId
        });
    }

    checkAuth(row: any) {
        if (this._isOperation) {
            const _level = this.$getUserLevel(row.createUserCategoryId || "");
            return ["ADMIN", "OPERATION_ADMIN", "OPERATION"].includes(
                _level.name
            );
        } else {
            return true;
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep {
    .pbb__search-box {
        margin-bottom: 10px;
    }
}
.table-header-filter {
    cursor: pointer;
}

.table-header-is-select {
    color: #077bff;
}

.regional-table-container {
    height: 100%;
}
</style>
